﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.Entity;

namespace Library
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    /// 
    public partial class MainWindow : Window
    {
        public DatabaseProxy MainDB = new DatabaseProxy();
        public bool eCopy;

        public static List<DepartmentsName> deptNames = new List<DepartmentsName>() 
            { 
                DepartmentsName.Registration,
                DepartmentsName.Storage,
                DepartmentsName.ReadingRoom,
                DepartmentsName.KidsRoom,
                DepartmentsName.BorrowRoom
            };
        public static List<Genre> genres = new List<Genre>() 
            {
                Genre.Crime,
                Genre.Esotericism,
                Genre.Fantasy,
                Genre.Fiction,
                Genre.Lyrics,
                Genre.Poetry,
                Genre.Romance,
                Genre.Science,
                Genre.Thriller
            };

        public MainWindow()
        {
            InitializeComponent();
            InitializeData();
        }

        public void InitializeData()
        {
            this.ClientsListView.ItemsSource = this.MainDB.LoadClients();
            this.BooksListView.ItemsSource = this.MainDB.LoadBooks();
            foreach (DepartmentsName deptName in deptNames)
            {
                this.DepartmentComboBox.Items.Add(deptName.ToString());
            }
            foreach (Genre gen in genres)
            {
                this.GenreComboBox.Items.Add(gen.ToString());
            }
        }

        public void ClientsListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string selectedClient = ClientsListView.SelectedItem.ToString();
            this.SelectedClientTextBox.Text = selectedClient;
            ClientTextInfo.Text = selectedClient;


        }

        private void AddClientButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Regenerator reg = new Regenerator();
                // MessageBox.Show(this.ClientAddressTextBox.Text);
                string clientFirstName = this.ClientFirstNameTextBox.Text;
                string clientLastName = this.ClientLastNameTextBox.Text;
                ulong clientEGN = ulong.Parse(this.ClientEGNTextBox.Text);
                string clientAddress = this.ClientAddressTextBox.Text;
                List<Client> existClient = reg.ClientRegenerator(clientEGN.ToString());
                if (existClient.Count != 0)
                {
                    throw new NotUniqueException("A client with this EGN already exist");
                }
                this.MainDB.StoreClient(new Client(clientFirstName, clientLastName, clientEGN, clientAddress));
                this.isClientAdded.Visibility = Visibility.Visible;
                this.ClientFirstNameTextBox.Text = "";
                this.ClientLastNameTextBox.Text = "";
                this.ClientEGNTextBox.Text = "";
                this.ClientAddressTextBox.Text = "";
                InitializeData();
            }
            catch (ArgumentNullException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (NotUniqueException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (FormatException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void AddBookButton_Click(object sender, RoutedEventArgs e)
        {
            Regenerator reg = new Regenerator();
            string bookTitle = this.TitleTextBox.Text;
            string bookAuthor = this.AuthorTextBox.Text;
            string bookIdNumber = this.IDNumberTextBox.Text;
            bool bookECopy = false;
            if ((bool)this.ECopyCheckBox.IsChecked)
            {
                bookECopy = true;
            }
            var dnValue = this.DepartmentComboBox.SelectedValue;
            var genValue = this.GenreComboBox.SelectedValue;
            try
            {
                if (dnValue != null || genValue != null)
                {
                    DepartmentsName dName = reg.StringToDepartmentsName(dnValue.ToString());
                    Genre bookGenre = reg.StringToGenre(genValue.ToString());
                    List<Book> existBook = reg.BookRegenerator(bookIdNumber);
                    if (existBook.Count != 0)
                    {
                        throw new NotUniqueException("A book with this ID number5 already exist");
                    }

                    Book newBook = new Book(bookTitle, bookAuthor, bookECopy, bookIdNumber, dName, bookGenre);

                    using(var ctx = new DBContext())
                    {
                        ctx.Books.Add(newBook);
                        ctx.SaveChanges();
                    }
                    //newBook.ECopy = this.eCopy;
                    this.MainDB.StoreBook(newBook);
                    this.TitleTextBox.Text = "";
                    this.AuthorTextBox.Text = "";
                    this.IDNumberTextBox.Text = "";
                    InitializeData();
                }
                else
                {
                    MessageBox.Show("Please select a Genre and a Department name.");
                }
            }
            catch (ArgumentNullException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (NotUniqueException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.ClientsTab.IsSelected = false;
            this.BooksTab.IsSelected = true;
        }

        private void BooksListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.BorrowBookButton.Visibility = Visibility.Visible;
        }

        private void BorrowBookButton_Click(object sender, RoutedEventArgs e)
        {
            string[] clientData = this.SelectedClientTextBox.Text.Split(' ');
            string[] splitEgn = clientData[1].Split('\n');
            string[] values = { clientData[0], splitEgn[0], splitEgn[1], clientData[2] };
            ulong EGNparsed = ulong.Parse(values[2]);
            Book bookToBorrow = this.BooksListView.SelectedItem as Book;
            bookToBorrow.AddNewBorrow(new Client(values[0], values[1], EGNparsed, values[3]));
            MessageBox.Show("Book borrowed by: " + values[0] + " " + values[1]);
        }

        private void ECopyCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            this.eCopy = true;
        }

        //<Grid>
        //          <ListView Margin="10" Name="lvUsers">
        //                  <ListView.View>
        //                          <GridView>
        //                                  <GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
        //                                  <GridViewColumn Header="Age" Width="50" DisplayMemberBinding="{Binding Age}" />
        //                                  <GridViewColumn Header="Mail" Width="150" DisplayMemberBinding="{Binding Mail}" />
        //                          </GridView>
        //                  </ListView.View>
        //          </ListView>
        //  </Grid>



    }
}